use std::collections::HashMap;
use std::path::Path;
use std::process::Command;

use crate::runtime::runtime::error::InternalError;
use crate::runtime::runtime::result::InternalErrorResult;

/// 执行本地系统脚本或命令
pub fn execute_system_command<P: AsRef<Path>>(cmd: &str, working: Option<P>, environments: Option<&HashMap<String, String>>) -> InternalErrorResult<()> {
    let mut command = Command::new("sh");
    command.arg("-c").arg(cmd);

    if working.is_some() {
        command.current_dir(working.unwrap());
    }

    if environments.is_some() {
        command.envs(environments.unwrap().into_iter());
    }

    let mut child = command.spawn().map_err(|e| InternalError::new(format!("Could not executing command: {}", e)))?;
    child.wait().map_err(|e| InternalError::new(format!("Could not executing command: {}", e)))?;

    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_execute_system_command() {
        let result = super::execute_system_command("echo hi", Option::<&str>::None, None);
        assert_eq!(true, result.is_ok());
    }
}